<script setup lang="ts">
import type { Rules } from 'async-validator'
import type { Config } from '~/types/system/config'
import { cloneDeep } from 'lodash-es'

const props = withDefaults(defineProps<{
  visible: boolean
  /** 修改时必传，角色基本数据 */
  data?: Config
}>(), {
  visible: false,
})

const emit = defineEmits<{
  (e: 'done'): void
  (e: 'update:visible', visible: boolean): void
}>()

const show = computed({
  get() {
    return props.visible
  },
  set(val: boolean) {
    emit('update:visible', val)
  },
})

const refForm = ref()
// 是否修改弹窗
const isUpdate = ref(false)
// 表单数据
const baseFormData = {
  id: undefined,
  name: '',
  code: '',
  describe: '',
}

const form = reactive<Config>({ ...baseFormData })
// 表单校验规则
const rules = ref<Rules>({
  // name: { type: 'string', required: true, message: '角色名不能为空' },
  // code: { type: 'string', required: true, message: '角色编码不能为空' },
})
interface DictItem {
  label: string
  value: number | string
}

const items4 = ref<DictItem[]>([])

/** 初始化表单数据 */
function initData() {
  if (props.data) {
    Object.assign(form, props.data)
    isUpdate.value = true
  } else {
    Object.assign(form, baseFormData)
    isUpdate.value = false
  }
}
// 修改 initItems 函数如下：
async function initItems() {
  const { success, data } = await getConfigDictItemApi('config_type')

  if (success && Array.isArray(data)) {
    items4.value = data.map((item: any) => {
      return {
        label: item.name,
        value: item.value,
      }
    })
  } else {
    items4.value = []
  }
}

/** 关闭弹窗 */
function handleClose() {
  // this.dialogVisible = false// 控制弹窗隐藏
  // $refs.formRef.resetFields() // 清空表单校验和数据（适用于 el-form
  // 重置表单
  // refForm.value.reset()
  // // 清空表单校验
  // refForm.value?.clearValidate()
  // 关闭弹窗
  show.value = false
}

/** 保存数据 */
async function saveData(model: Config, layerId: string) {
  try {
    // 新增用户
    const { success, message } = await addConfigDictItemApi({
      ...cloneDeep(model) as Config,
    })
    if (!success) {
      layer.msg(message || '操作失败', { icon: 2 })
      return
    }

    layer.msg(message || '操作成功', { icon: 1 })
    // 关闭loading
    layer.close(layerId)
    // 关闭弹窗
    handleClose()
  } catch (e) {
    layer.close(layerId)
    layer.msg((e as Error).message, { icon: 2 })
  }
}

/** 修改数据 */
async function updateData(model: Config, layerId: string) {
  try {
    const { success, message } = await updateConfigApi({
      ...cloneDeep(model) as Config,
    })
    if (!success) {
      layer.msg(message || '操作失败', { icon: 2 })
      return
    }

    layer.msg(message || '操作成功', { icon: 1 })

    layer.close(layerId)
    // 关闭弹窗
    handleClose()
  } catch (e) {
    layer.close(layerId)
    layer.msg((e as Error).message, { icon: 2 })
  }
}

async function changeState(val: number) {
  form.configState = val
}
/** 表单提交 */
function handleSubmit() {
  layer.msg('正在提交数据...', { icon: 16 }, async (layerId: string) => {

    isUpdate.value
      ? await updateData(form, layerId)
      : await saveData(form, layerId)
    emit('done')
  })
}

watch(
  () => props.visible,
  (visible: boolean) => {
    if (visible) {
      // 初始化弹窗数据
      initData()
      initItems()
    }
  },
)
</script>

<template>
  <lay-layer
    v-model="show"
    area="500px"
    :title="isUpdate ? '编辑' : '新增'"
    :shade-close="false"
    :move="true"
    :maxmin="true"
    :btn="[
      { text: '提交', callback: () => handleSubmit() },
      { text: '关闭', callback: () => handleClose() },
    ]"
    @close="handleClose"
  >
    <lay-form :model="form" :rules="rules" style="padding: 10px">
      <lay-form-item label="配置名称" prop="account">
        <lay-input v-model="form.configName" placeholder="请填写" allow-clear />
      </lay-form-item>
      <lay-form-item label="配置类型" prop="account">
        <lay-select
          v-model="form.configType" :show-search="true"
          :items="items4" :options="items4"
          :allow-clear="true"
        >
        </lay-select>
      </lay-form-item>
      <lay-form-item label="配置键" prop="code">
        <lay-input v-model="form.configKey" placeholder="请填写" allow-clear />
      </lay-form-item>
      <lay-form-item label="配置值" prop="describe">
        <lay-textarea v-model="form.configValue" placeholder="请填写" allow-clear />
      </lay-form-item>
      <lay-form-item label="配置描述" prop="describe">
        <lay-textarea v-model="form.description" placeholder="请填写" allow-clear />
      </lay-form-item>
      <lay-form-item label="配置状态" prop="describe">
        <lay-switch
          :model-value="form.configState"
          onswitch-text="启用"
          :onswitch-value="1"
          unswitch-text="停用"
          :unswitch-value="0"
          @change="(val: number) => changeState(val)"
        />
      </lay-form-item>
    </lay-form>
  </lay-layer>
</template>
